package com.yaowk.utils.druid.config;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

@Configuration
public class DruidConfiguration {

    @Value("${yaowk.utils.druid.allow:}")
    private String allow; // 允许的ip
    @Value("${yaowk.utils.druid.deny:}")
    private String deny; // 禁止的ip
    @Value("${yaowk.utils.druid.username:druid}")
    private String username; // druid监控器登录用户名
    @Value("${yaowk.utils.druid.password:123456}")
    private String password; // druid监控器登录密码
    @Value("${yaowk.utils.druid.resetEnable:false}")
    private String resetEnable;


    @Bean
    public ServletRegistrationBean statViewServlet() {
        //创建servlet注册实体
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        //设置ip白名单
        if (!StringUtils.isEmpty(allow))
            servletRegistrationBean.addInitParameter("allow", allow);
        //设置ip黑名单，如果allow与deny共同存在时,deny优先于allow
        if (!StringUtils.isEmpty(deny))
            servletRegistrationBean.addInitParameter("deny", deny);
        //设置控制台管理用户
        if (!StringUtils.isEmpty(username))
            servletRegistrationBean.addInitParameter("loginUsername", username);
        if (!StringUtils.isEmpty(password))
            servletRegistrationBean.addInitParameter("loginPassword", password);
        //是否可以重置数据
        servletRegistrationBean.addInitParameter("resetEnable", resetEnable);
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean statFilter() {
        //创建过滤器
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        //设置过滤器过滤路径
        filterRegistrationBean.addUrlPatterns("/*");
        //忽略过滤的形式
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}
